package XMLtest.stu;

import org.w3c.dom.*;
import org.xml.sax.SAXException;

import javax.print.Doc;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.*;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;

public class StuXML {

    public static void main(String[] args) {
        File file = new File("src/XMLtest/stu/stu.xml");
        StuXML stu = new StuXML();
        Document doc = stu.parse(file);


        //修改节点，修改第一个学生的ID
//        NodeList nl = doc.getDocumentElement().getElementsByTagName("student");
//        Node n = nl.item(0);//第一个学生元素的节点
//        Element e = (Element) n;
//        e.setAttribute("ID","123");


        //节点删除
//        doc.getDocumentElement().removeChild(eleStu);


//        Student student = new Student("赵柳","11111","男",18,100);
//        addStudent(doc,student);

        //保存
//        stu.saveXML(doc,"stu2.xml");
        stu.saveXML2(doc,"newStu.xml");

        if(doc!=null){
            ArrayList<Student> stus = stu.searchAllStus(doc);
            for (Student s:stus) {
                System.out.println(s);

            }
        }

    }

    public Document parse(File file){
        DocumentBuilderFactory fac = DocumentBuilderFactory.newInstance();
        Document doc = null;
        try {
            DocumentBuilder builder = fac.newDocumentBuilder();
            doc = builder.parse(file);
        } catch (ParserConfigurationException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (SAXException | IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return doc;
    }

    //查找所有学生
    public ArrayList<Student> searchAllStus(Document doc){
        ArrayList<Student> stuList = new ArrayList<Student>();
        NodeList nl = doc.getElementsByTagName("student");
        for (int i = 0; i < nl.getLength(); i++) {
            Node node = nl.item(i);
            Element e = (Element) node;

            String id = e.getAttribute("ID");
            String sex= e.getAttribute("sex");

            NodeList nll = e.getElementsByTagName("name");
            Element eName = (Element) nll.item(0);
            String name = eName.getTextContent();

            NodeList  nll2= e.getElementsByTagName("age");
            Element eAge = (Element) nll2.item(0);
            int age = Integer.parseInt(eAge.getTextContent());

            NodeList nll3 = e.getElementsByTagName("score");
            Element eScore = (Element) nll3.item(0);
            int score = Integer.parseInt(eScore.getTextContent());

            Student s = new Student(name,id,sex,age,score);
            stuList.add(s);

        }
        return stuList;
    }


    public static void addStudent(Document doc, Student stu){
        //添加学生节点
        Text newName = doc.createTextNode(stu.getName());//文本节点
        Text newAge = doc.createTextNode(String.valueOf(stu.getAge()));//文本节点
        Text newScore = doc.createTextNode(String.valueOf(stu.getScore()));//文本节点

        Element eleName = doc.createElement("name");//name元素节点，为空
        Element eleStu = doc.createElement("student");//student元素节点，为空
        Element eleSex = doc.createElement("sex");
        Element eleAge = doc.createElement("age");
        Element eleScore = doc.createElement("score");

        Attr a = doc.createAttribute("ID");
        a.setValue(stu.getId());
//        Attr a2 = doc.createAttribute("sex");//等价于下面方法
//        a2.setValue("男");
        //搭建元素层次的关系
        eleName.appendChild(newName);
        eleAge.appendChild(newAge);
        eleScore.appendChild(newScore);
        eleStu.setAttributeNodeNS(a);
        eleStu.setAttribute("sex",stu.getSex());
        eleStu.appendChild(eleName);
        eleStu.appendChild(eleAge);
        eleStu.appendChild(eleScore);

        doc.getDocumentElement().appendChild(eleStu);//根元素添加元素


    }

    public void saveXML(Document doc,String filename){
        TransformerFactory tff = TransformerFactory.newInstance();
        try {

            Transformer tf = tff.newTransformer();
            //设置输出xml的换行
            tf.setOutputProperty(OutputKeys.INDENT,"yes");
            //设置输出xml的缩进
            tf.setOutputProperty("{http://xml.apache.org/xslt}indent-amount","4");
            DOMSource source = new DOMSource(doc);
            StreamResult result = new StreamResult(new File("src/XMLtest/stu",filename));
            tf.transform(source,result);

        } catch (TransformerConfigurationException e) {
            e.printStackTrace();
        } catch (TransformerException e) {
            e.printStackTrace();
        }

    }
    public void saveXML2(Document doc,String filename){
        TransformerFactory tff = TransformerFactory.newInstance();
        DocumentBuilderFactory factory =DocumentBuilderFactory.newInstance();
        try {
            DocumentBuilder builder=factory.newDocumentBuilder();
            Document documnet= builder.newDocument();
            Element root=documnet.createElement("学生们");

            NodeList nl = doc.getElementsByTagName("student");
            for (int i = 0; i < nl.getLength(); i++) {
                Node node = nl.item(i);
                Element e = (Element) node;

                String id = e.getAttribute("ID");
                String sex = e.getAttribute("sex");

                NodeList nll = e.getElementsByTagName("name");
                Element eName = (Element) nll.item(0);
                String name = eName.getTextContent();

        Text newName = documnet.createTextNode(name);//文本节点

        Element eleName = documnet.createElement("姓名");//name元素节点，为空
        Element eleStu = documnet.createElement("学生");//student元素节点，为空
        //搭建元素层次的关系
        eleName.appendChild(newName);
        eleStu.setAttribute("学号",id);
        eleStu.setAttribute("性别",sex);
        eleStu.appendChild(eleName);

        root.appendChild(eleStu);//根元素添加元素
        }
        documnet.appendChild(root);

            Transformer tf = tff.newTransformer();
            //设置输出xml的换行
            tf.setOutputProperty(OutputKeys.INDENT,"yes");
            //设置输出xml的缩进
            tf.setOutputProperty("{http://xml.apache.org/xslt}indent-amount","4");
            DOMSource source = new DOMSource(documnet);
            StreamResult result = new StreamResult(new File("src/XMLtest/stu",filename));
            tf.transform(source,result);

        } catch (TransformerConfigurationException e) {
            e.printStackTrace();
        } catch (TransformerException e) {
            e.printStackTrace();
        } catch (ParserConfigurationException e) {
            e.printStackTrace();
        }

    }


}
